package cn.yuanqiao.archive.bianyan.service.Impl;

import cn.yuanqiao.archive.appManager.mapper.TenantSysConfigMapper;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.bianyan.domain.YqZhuanTi;
import cn.yuanqiao.archive.bianyan.domain.YqZhuanTiBlob;
import cn.yuanqiao.archive.bianyan.domain.YqZtcgFile;
import cn.yuanqiao.archive.bianyan.mapper.YqZhuanTiBlobMapper;
import cn.yuanqiao.archive.bianyan.mapper.YqZhuanTiMapper;
import cn.yuanqiao.archive.bianyan.mapper.YqZtcgFileMapper;
import cn.yuanqiao.archive.bianyan.service.IYqZhuanTiService;
import cn.yuanqiao.archive.bianyan.utils.PictureUploadUtils;
import cn.yuanqiao.common.constant.Constants;
import cn.yuanqiao.common.core.domain.R;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.exception.file.FileSizeLimitExceededException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.file.FileUtils;
import cn.yuanqiao.common.core.domain.AjaxResult;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.system.domain.SysFile;
import org.apache.poi.util.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * @ProjectName: ruoyi-modules-system
 * @Package: cn.yuanqiao.archive.bianyan.service.Impl
 * @ClassName: YqZhuanTiServiceImpl
 * @Author: lenovo
 * @Description: hbWang
 * @Date: 2023/7/5 9:24
 * @Version: 1.0
 */
@Service
public class YqZhuanTiServiceImpl implements IYqZhuanTiService {

    @Autowired
    private YqZhuanTiMapper yqZhuanTiMapper;

    @Autowired
    private YqZtcgFileMapper ztcgFileMapper;

    @Autowired
    private YqZhuanTiBlobMapper yqZhuanTiBlobMapper;

    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private TenantSysConfigMapper configMapper;

    /**
     * 查询专题
     *
     * @param typeId 专题主键
     * @return 专题
     */
    @Override
    public YqZhuanTi selectYqZhuanTiByTypeId(String typeId) {
        //获取数据库表 SecurityUtils.getTenantCode()
        String tableCode = SecurityUtils.getTenantCode().toUpperCase();
        String tableNameZt = tableCode + Constants.TABLE_YQ_ZHUAN_TI;
        YqZhuanTi yqZhuanTi = yqZhuanTiMapper.selectZhuanTiByTypeId(typeId, tableNameZt);
        return yqZhuanTi;
    }

    /**
     * 查询专题列表
     *
     * @param yqZhuanTi 专题
     * @return 专题
     */
    @Override
    public List<YqZhuanTi> selectYqZhuanTiList(YqZhuanTi yqZhuanTi) {
        //获取数据库表 SecurityUtils.getTenantCode()
        String tableCode = SecurityUtils.getTenantCode().toUpperCase();
        String tableNameZt = tableCode + Constants.TABLE_YQ_ZHUAN_TI;
        return yqZhuanTiMapper.selectZhuanTiList(yqZhuanTi, tableNameZt);
    }


    /**
     * 新增专题
     *
     * @param yqZhuanTi 专题
     * @return 结果
     */
    @Override
    public AjaxResult insertYqZhuanTi(YqZhuanTi yqZhuanTi) {
        //获取数据库表 SecurityUtils.getTenantCode()
        String tableCode = SecurityUtils.getTenantCode().toUpperCase();
        String tableNameZt = tableCode + Constants.TABLE_YQ_ZHUAN_TI;
        List zhuanTis = yqZhuanTiMapper.selectZhuanTiByTypeName(yqZhuanTi.getTypeName(), tableNameZt, SecurityUtils.getUserId());
        if (zhuanTis != null && zhuanTis.size() > 0) {
            AjaxResult.error(500, "专题名称重复");
        }
        yqZhuanTi.setTypeId(String.valueOf(SnowflakeIdGenerator.generateId()));
        yqZhuanTi.setCreateTime(DateUtils.getNowDate());
        yqZhuanTi.setState("0");
        yqZhuanTi.setIsDel("0");
        yqZhuanTi.setCreateUser(String.valueOf(SecurityUtils.getUserId()));
        int i = yqZhuanTiMapper.insertZhuanTi(yqZhuanTi, tableNameZt);
        return i > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 新增专题明细
     *
     * @param yqZhuanTiBlob 专题明细
     * @return 结果
     */
    @Override
    public int insertYqZhuanTiBlob(YqZhuanTiBlob yqZhuanTiBlob) {
        //获取数据库表 SecurityUtils.getTenantCode()
        String tableCode = SecurityUtils.getTenantCode().toUpperCase();
        String tableName = tableCode + Constants.TABLE_YQ_ZHUAN_TI_BLOB;
        return yqZhuanTiBlobMapper.insertYqZhuanTiBlob(yqZhuanTiBlob, tableName);
    }

    /**
     * 修改专题
     *
     * @param yqZhuanTi 专题
     * @return 结果
     */
    @Override
    public int updateYqZhuanTi(YqZhuanTi yqZhuanTi) {
        //获取数据库表 SecurityUtils.getTenantCode()
        String tableCode = SecurityUtils.getTenantCode().toUpperCase();
        String tableNameZt = tableCode + Constants.TABLE_YQ_ZHUAN_TI;

        if (!StringUtils.isEmpty(yqZhuanTi.getState()) && "2".equals(yqZhuanTi.getState())) {
            yqZhuanTi.setCategoryIds("");
            yqZhuanTi.setMaterialIds("");
            yqZhuanTi.setArchiveIds("");
        }
        return yqZhuanTiMapper.updateZhuanTi(yqZhuanTi, tableNameZt);
    }

    /**
     * 批量删除专题
     *
     * @param typeIds 需要删除的专题主键
     * @return 结果
     */
    @Override
    public int deleteYqZhuanTiByTypeIds(String[] typeIds) {
        //获取数据库表 SecurityUtils.getTenantCode()
        String tableCode = SecurityUtils.getTenantCode().toUpperCase();
        String tableNameZt = tableCode + Constants.TABLE_YQ_ZHUAN_TI;

        return yqZhuanTiMapper.deleteZhuanTiByTypeIds(typeIds, tableNameZt);
    }

    /**
     * 删除专题信息
     *
     * @param typeId 专题主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteYqZhuanTiByTypeId(String typeId) {
        //获取数据库表 SecurityUtils.getTenantCode()
        String tableCode = SecurityUtils.getTenantCode().toUpperCase();
        String tableName = tableCode + Constants.TABLE_YQ_ZHUAN_TI_BLOB;
        String tableNameZt = tableCode + Constants.TABLE_YQ_ZHUAN_TI;
        YqZhuanTi yqZhuanTi = yqZhuanTiMapper.selectZhuanTiByTyPeparentId(typeId, tableNameZt);
        if (yqZhuanTi != null) {
             throw new ServiceException("请先删除子节点,后在进行删除");
        }
        yqZhuanTiBlobMapper.deleteYqZhuanTiBlobByTypeId(typeId, tableName);
        return yqZhuanTiMapper.deleteZhuanTiByTypeId(typeId, tableNameZt);
    }

    /**
     * 上传封面
     *
     * @param file
     * @return
     */
    @Override
    public R<SysFile> uploadPicture(MultipartFile file) {
        String uplodPath = sysConfigService.selectConfigByKey("YQ_ZT_PATH");
        String uplodMaxs = sysConfigService.selectConfigByKey("DA_FILE_MAX");
        long uplodMax = 50 * 1024 * 1024;
        if (org.apache.commons.lang3.StringUtils.isNotBlank(uplodMaxs)) {
            uplodMax = Long.valueOf(uplodMaxs) * 1024 * 1024;
        }
        long size = file.getSize();
        if (size > uplodMax) {
            throw new FileSizeLimitExceededException(uplodMax / 1024 / 1024);
        }
        try {
//            TenantSysConfig config = new TenantSysConfig();
//            config.setConfigKey("YQ_MNT");
//            config.setTenantCode(SecurityUtils.getLoginUser().getUser().getTenantCode());
//            TenantSysConfig retConfig = configMapper.selectConfig(config);

            // 上传并返回访问地址
            String url = PictureUploadUtils.upload(uplodPath, file);
            SysFile sysFile = new SysFile();
            sysFile.setName(FileUtils.getName(url));
            sysFile.setUrl(url);
            sysFile.setSize(PictureUploadUtils.bytesTrans(file.getSize()));
            return R.ok(sysFile);
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    /**
     * 预览
     *
     * @param
     * @return cn.yuanqiao.common.core.domain.R<cn.yuanqiao.common.core.domain.entity.SysFile>
     * @author hbWang
     * @date 2023/9/15 16:26
     */
    @Override
    public byte[] queryImage(String typeId, String type) {
        String tableCode = SecurityUtils.getTenantCode();
        String uplodPath = sysConfigService.selectConfigByKey("YQ_ZT_PATH");
        if ("1".equals(type)) {
            YqZhuanTi yqZhuanTi = selectYqZhuanTiByTypeId(typeId);
            uplodPath = uplodPath + yqZhuanTi.getCoverPath();
        }
        if ("2".equals(type)) {
            YqZtcgFile yqZtcgFile = ztcgFileMapper.selectYqZtcgFileById(typeId, tableCode + Constants.TABLE_YQ_ZTCG_FILE);
            uplodPath = uplodPath + yqZtcgFile.getFilePath();
        }
        return readFile(uplodPath);
    }

    /**
     * 删除文件
     *
     * @param filePath
     * @return
     */
    @Override
    public boolean fileDelete(String filePath) {
        String uplodPath = sysConfigService.selectConfigByKey("YQ_ZT_PATH");
        File file = new File(uplodPath + filePath);
        int suffix = filePath.lastIndexOf(".");
        if (suffix < 0) {
            return false;
        }
        if (file.exists()) {
            //如果文件存在就删除文件
            file.delete();
            return true;
        }
        return false;
    }

    /**
     * 查询专题树
     *
     * @param typeName 专题名称
     * @return 专题
     */
    @Override
    public List<YqZhuanTi> selectYqZhuanTiTree(String typeName) {
        //获取数据库表 SecurityUtils.getTenantCode()
        String tableCode = SecurityUtils.getTenantCode().toUpperCase();
        String tableNameZt = tableCode + Constants.TABLE_YQ_ZHUAN_TI;
        List<YqZhuanTi> yqZhuanTis = yqZhuanTiMapper.selectZhuanTiByTypeName(typeName, tableNameZt, SecurityUtils.getUserId());
        return buildYqZhuanTiTree(yqZhuanTis);
    }

    @Override
    public List<YqZhuanTi> selectYqZhuanTiTreeByPid(Long id) {
        //获取数据库表 SecurityUtils.getTenantCode()
        String tableCode = SecurityUtils.getTenantCode().toUpperCase();
        String tableNameZt = tableCode + Constants.TABLE_YQ_ZHUAN_TI;
        List<YqZhuanTi> yqZhuanTis = yqZhuanTiMapper.selectYqZhuanTiTreeByPid(id, tableNameZt, SecurityUtils.getUserId(), SecurityUtils.getTenantCode().toUpperCase());
        return buildYqZhuanTiTree(yqZhuanTis);
    }

    @Override
    public List<YqZhuanTi> getTree(Long id) {
        //获取数据库表 SecurityUtils.getTenantCode()
        String tableCode = SecurityUtils.getTenantCode().toUpperCase();
        String tableNameZt = tableCode + Constants.TABLE_YQ_ZHUAN_TI;
        List<YqZhuanTi> yqZhuanTis = yqZhuanTiMapper.getTree(id, tableNameZt);
        return buildYqZhuanTiTree(yqZhuanTis);
    }

    /**
     * 递归处理树结构
     *
     * @param
     * @return java.util.List<cn.yuanqiao.archive.bianyan.domain.YqZhuanTi>
     * @author hbWang
     * @date 2023/7/5 10:16
     */
    public List<YqZhuanTi> buildYqZhuanTiTree(List<YqZhuanTi> yqZhuanTis) {
        List<YqZhuanTi> returnList = new ArrayList<>();
        List<String> tempList = new ArrayList<>();
        YqZhuanTi TREE0 = new YqZhuanTi();
        TREE0.setTypeId("0");
        TREE0.setTypeName("专题库");
        TREE0.setParentId("-1");
        yqZhuanTis.add(TREE0);
        for (YqZhuanTi yqZhuanTi : yqZhuanTis) {
            tempList.add(yqZhuanTi.getTypeId());
        }
        for (Iterator<YqZhuanTi> iterator = yqZhuanTis.iterator(); iterator.hasNext(); ) {
            YqZhuanTi yqZhuanTi = iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(yqZhuanTi.getParentId())) {
                recursionFn(yqZhuanTis, yqZhuanTi);
                returnList.add(yqZhuanTi);
            }
        }
        if (returnList.isEmpty()) {
            returnList = yqZhuanTis;
        }
        return returnList;
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<YqZhuanTi> list, YqZhuanTi t) {
        // 得到子节点列表
        List<YqZhuanTi> childList = getChildList(list, t);
        t.setChildren(childList);
        for (YqZhuanTi tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<YqZhuanTi> getChildList(List<YqZhuanTi> list, YqZhuanTi t) {
        List<YqZhuanTi> tlist = new ArrayList<>();
        Iterator<YqZhuanTi> it = list.iterator();
        while (it.hasNext()) {
            YqZhuanTi n = it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().equals(t.getTypeId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<YqZhuanTi> list, YqZhuanTi t) {
        return getChildList(list, t).size() > 0 ? true : false;
    }


    /**
     * 读取文件为字节数据
     *
     * @param url 地址
     * @return 字节数据
     */
    private static byte[] readFile(String url) {
        InputStream in = null;
        ByteArrayOutputStream baos = null;
        try {
            // 本机地址
            in = new FileInputStream(url);

            return IOUtils.toByteArray(in);
        } catch (
                Exception e) {

            return null;
        } finally {
            IOUtils.closeQuietly(baos);
        }
    }

}
